package com.ruoyi.statistics.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.statistics.service.IUserAnalyseService;

/**
 * 用户数据分析Controller
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@Anonymous
@RestController
@RequestMapping("/statistics/userAnalyse")
public class UserAnalyseController extends BaseController
{
    @Autowired
    private IUserAnalyseService userAnalyseService;

    /**
     * 获取用户核心指标数据
     */
    @GetMapping("/metrics")
    public AjaxResult getUserMetrics(
            @RequestParam(value = "orgId", required = false) Long orgId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate)
    {
        Map<String, Object> params = new HashMap<>();
        // 使用当前用户的组织ID，忽略传入的orgId参数
        params.put("orgId", getDeptId());
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        Map<String, Object> metrics = userAnalyseService.selectUserMetrics(params);
        return AjaxResult.success(metrics);
    }

    /**
     * 获取用户活跃度趋势数据
     */
    @GetMapping("/activityTrend")
    public AjaxResult getUserActivityTrend(
            @RequestParam(value = "orgId", required = false) Long orgId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "timeType", defaultValue = "day") String timeType)
    {
        Map<String, Object> params = new HashMap<>();
        // 使用当前用户的组织ID，忽略传入的orgId参数
        params.put("orgId", getDeptId());
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("timeType", timeType);
        List<Map<String, Object>> trendData = userAnalyseService.selectUserActivityTrend(params);
        return AjaxResult.success(trendData);
    }

    /**
     * 获取用户地域分布数据
     */
    @GetMapping("/regionDistribution")
    public AjaxResult getUserRegionDistribution(
            @RequestParam(value = "orgId", required = false) Long orgId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate)
    {
        Map<String, Object> params = new HashMap<>();
        // 使用当前用户的组织ID，忽略传入的orgId参数
        params.put("orgId", getDeptId());
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        List<Map<String, Object>> regionData = userAnalyseService.selectUserRegionDistribution(params);
        return AjaxResult.success(regionData);
    }

    /**
     * 获取用户转化漏斗数据
     */
    @GetMapping("/conversionFunnel")
    public AjaxResult getUserConversionFunnel(
            @RequestParam(value = "orgId", required = false) Long orgId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate)
    {
        Map<String, Object> params = new HashMap<>();
        // 使用当前用户的组织ID，忽略传入的orgId参数
        params.put("orgId", getDeptId());
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        try {
            Map<String, Object> funnelData = userAnalyseService.selectUserConversionFunnel(params);
            
            // 转换为前端期望的数组格式
            List<Map<String, Object>> funnelList = new ArrayList<>();
            
            if (funnelData != null) {
                // 获取各阶段数据
                long visitUserCount = parseLong(funnelData.get("visitUserCount"));
                long registerUserCount = parseLong(funnelData.get("registerUserCount"));
                long orderUserCount = parseLong(funnelData.get("orderUserCount"));
                long payUserCount = parseLong(funnelData.get("payUserCount"));
                
                // 确保转化漏斗数据符合逻辑（下级不超过上级）
                registerUserCount = Math.min(registerUserCount, visitUserCount);
                orderUserCount = Math.min(orderUserCount, registerUserCount);
                payUserCount = Math.min(payUserCount, orderUserCount);
                
                // 构建转化漏斗数组
                funnelList.add(createFunnelStage("浏览用户", visitUserCount, "100%"));
                funnelList.add(createFunnelStage("注册用户", registerUserCount, calculateRate(registerUserCount, visitUserCount)));
                funnelList.add(createFunnelStage("下单用户", orderUserCount, calculateRate(orderUserCount, registerUserCount)));
                funnelList.add(createFunnelStage("付费用户", payUserCount, calculateRate(payUserCount, orderUserCount)));
            }
            
            return AjaxResult.success(funnelList);
        } catch (Exception e) {
            logger.error("获取用户转化漏斗数据失败", e);
            return AjaxResult.error("获取用户转化漏斗数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户详情列表
     */
    @GetMapping("/details")
    public TableDataInfo getUserDetails(
            @RequestParam(value = "orgId", required = false) Long orgId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "userName", required = false) String userName,
            @RequestParam(value = "sortField", required = false) String sortField,
            @RequestParam(value = "sortOrder", required = false) String sortOrder)
    {
        // 构建筛选参数
        Map<String, Object> params = new HashMap<>();
        // 使用当前用户的组织ID，忽略传入的orgId参数
        params.put("orgId", getDeptId());
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        params.put("userName", userName);
        params.put("sortField", sortField);
        params.put("sortOrder", sortOrder);
        
        List<Map<String, Object>> rows = userAnalyseService.selectUserDetails(params);
        Integer total = userAnalyseService.selectUserDetailsCount(params);
        
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setRows(rows);
        dataInfo.setTotal(total);
        dataInfo.setCode(200);
        dataInfo.setMsg("查询成功");
        
        return dataInfo;
    }

    /**
     * 导出用户数据分析
     */
    @Log(title = "用户数据分析", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,
            @RequestParam(value = "orgId", required = false) Long orgId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "userName", required = false) String userName,
            @RequestParam(value = "userStatus", required = false) String userStatus,
            @RequestParam(value = "province", required = false) String province,
            @RequestParam(value = "orderAmountMin", required = false) String orderAmountMin,
            @RequestParam(value = "orderAmountMax", required = false) String orderAmountMax)
    {
        try {
            // 构建筛选参数
            Map<String, Object> params = new HashMap<>();
            // 使用当前用户的组织ID，忽略传入的orgId参数
            params.put("orgId", getDeptId());
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("userName", userName);
            params.put("userStatus", userStatus);
            params.put("province", province);
            params.put("orderAmountMin", orderAmountMin);
            params.put("orderAmountMax", orderAmountMax);
            
            List<Map<String, Object>> exportData = userAnalyseService.selectUserDetailsForExport(params);
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = java.net.URLEncoder.encode("用户详情数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户详情数据");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户ID", "用户名称", "昵称", "浏览次数", "常用设备", "注册时间", "所在省份", "订单数量", "消费金额", "用户状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            
            // 填充数据
            for (int i = 0; i < exportData.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Map<String, Object> data = exportData.get(i);
                row.createCell(0).setCellValue(String.valueOf(data.get("用户ID")));
                row.createCell(1).setCellValue(String.valueOf(data.get("用户名称")));
                row.createCell(2).setCellValue(String.valueOf(data.get("昵称")));
                row.createCell(3).setCellValue(String.valueOf(data.get("浏览次数")));
                row.createCell(4).setCellValue(String.valueOf(data.get("常用设备")));
                row.createCell(5).setCellValue(String.valueOf(data.get("注册时间")));
                row.createCell(6).setCellValue(String.valueOf(data.get("所在省份")));
                row.createCell(7).setCellValue(String.valueOf(data.get("订单数量")));
                row.createCell(8).setCellValue(String.valueOf(data.get("消费金额")));
                row.createCell(9).setCellValue(String.valueOf(data.get("用户状态")));
            }
            
            // 输出到响应流
            workbook.write(response.getOutputStream());
            workbook.close();
            
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取商品评价核心指标
     */
    @GetMapping("/comment/statistics")
    public AjaxResult getCommentStatistics(@RequestParam(required = false) String startTime,
                                         @RequestParam(required = false) String endTime,
                                         @RequestParam(required = false) String productId)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("productId", productId);
        // 添加组织ID过滤
        params.put("orgId", getDeptId());
        
        Map<String, Object> data = userAnalyseService.selectCommentStatistics(params);
        return AjaxResult.success(data);
    }

    /**
     * 获取评价评分分布数据
     */
    @GetMapping("/comment/rating-distribution")
    public AjaxResult getCommentRatingDistribution(@RequestParam(required = false) String startTime,
                                                 @RequestParam(required = false) String endTime,
                                                 @RequestParam(required = false) String productId)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("productId", productId);
        // 添加组织ID过滤
        params.put("orgId", getDeptId());
        
        List<Map<String, Object>> data = userAnalyseService.selectCommentRatingDistribution(params);
        return AjaxResult.success(data);
    }

    /**
     * 获取售后处理核心指标
     */
    @GetMapping("/afterservice/statistics")
    public AjaxResult getAfterServiceStatistics(@RequestParam(required = false) String startTime,
                                              @RequestParam(required = false) String endTime,
                                              @RequestParam(required = false) String orderId)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("orderId", orderId);
        // 添加组织ID过滤
        params.put("orgId", getDeptId());
        
        Map<String, Object> data = userAnalyseService.selectAfterServiceStatistics(params);
        return AjaxResult.success(data);
    }

    /**
     * 获取售后问题分类数据
     */
    @GetMapping("/afterservice/category")
    public AjaxResult getAfterServiceCategory(@RequestParam(required = false) String startTime,
                                            @RequestParam(required = false) String endTime,
                                            @RequestParam(required = false) String orderId)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("orderId", orderId);
        // 添加组织ID过滤
        params.put("orgId", getDeptId());
        
        List<Map<String, Object>> data = userAnalyseService.selectAfterServiceCategory(params);
        return AjaxResult.success(data);
    }

    /**
     * 获取评价关键词统计（用于词云图）
     */
    @GetMapping("/comment/keywords")
    public AjaxResult getCommentKeywords(@RequestParam(required = false) String startTime,
                                       @RequestParam(required = false) String endTime,
                                       @RequestParam(required = false) String productId,
                                       @RequestParam(required = false) String sentiment)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("productId", productId);
        params.put("sentiment", sentiment);
        // 添加组织ID过滤
        params.put("orgId", getDeptId());

        List<Map<String, Object>> data = userAnalyseService.selectCommentKeywords(params);
        return AjaxResult.success(data);
    }
    
    /**
     * 创建转化漏斗阶段数据
     */
    private Map<String, Object> createFunnelStage(String stage, long value, String rate) {
        Map<String, Object> stageData = new HashMap<>();
        stageData.put("stage", stage);
        stageData.put("value", value);
        stageData.put("rate", rate);
        return stageData;
    }
    
    /**
     * 计算转化率
     */
    private String calculateRate(long current, long previous) {
        if (previous == 0) {
            return "0%";
        }
        double rate = (double) current / previous * 100;
        return String.format("%.1f%%", Math.min(rate, 100.0));
    }
    
    /**
     * 安全解析long值
     */
    private long parseLong(Object value) {
        if (value == null) {
            return 0L;
        }
        try {
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            return 0L;
        }
    }
}